package com.dict.receivers;

import java.net.URL;
import java.util.Calendar;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.dict.DictionaryActivity;
import com.dict.R;
import com.dict.WotdXMLHandler;
import com.dict.XMLList;

public class AlarmReceiver extends BroadcastReceiver {

	 private Calendar cal ;
	    private XMLList list;
	    private Context ctx;
	    
	@Override
	public void onReceive(Context arg0, Intent arg1) {
		
		Log.d("RECEIVER", "YAWN! Good Morning!");
		
		ctx = arg0;
		getWordOfTheDay();
		
	}
	
private void getWordOfTheDay(){
		
		//i.putExtra("NotifID", 1);
		Calendar cal = Calendar.getInstance();
		int day=cal.get(Calendar.DAY_OF_MONTH);
		int month=cal.get(Calendar.MONTH);
		int year=cal.get(Calendar.YEAR);

		

		NotificationManager nm = (NotificationManager)
				ctx.getSystemService(Context.NOTIFICATION_SERVICE);
		
		Notification notif = new Notification(
				R.drawable.dict, 
				"Word Of The Day",
				System.currentTimeMillis());
		
		notif.defaults |= Notification.DEFAULT_SOUND;
		notif.defaults |= Notification.DEFAULT_VIBRATE;
		notif.defaults |= Notification.FLAG_AUTO_CANCEL;

		try {

			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL(
					"http://api-pub.dictionary.com/v001?vid=aqjxh56ojb1b2yxervp0dzx3he1kmp3xfnuws1lccn&type=wotd&day="+day+"&month="+month+"&year="+year+"&lang=en_US");

			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			WotdXMLHandler handler = new WotdXMLHandler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(sourceUrl.openStream()));

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}
		list = (XMLList)WotdXMLHandler.list;

		CharSequence from = "Word Of The Day";
		CharSequence message = list.getWord().toString();  
		
		Log.d("RECEIVER", "TOday's Word: " + message);
		
		Intent i = new Intent (ctx, DictionaryActivity.class);
		i.putExtra("word", message);
		
		PendingIntent detailsIntent = PendingIntent.getActivity(ctx, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
		
		notif.setLatestEventInfo(ctx, from, message, detailsIntent);
		//i.putExtra("word", message);
		nm.notify(1, notif);
		
		

	}

}
